"""
SuperTokens authentication routes for LandPPT
"""

from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from supertokens_python.recipe.session.framework.fastapi import verify_session
from supertokens_python.recipe.session import SessionContainer
import logging

logger = logging.getLogger(__name__)

router = APIRouter()
templates = Jinja2Templates(directory="src/landppt/web/templates")

# Helper function to create context processor for templates
def get_template_context(request: Request):
    """Get additional template context including url_for function"""
    root_path = request.scope.get("root_path", "")
    
    def url_for(path: str):
        """Generate URL with proper root_path prefix"""
        if not path.startswith("/"):
            path = f"/{path}"
        if root_path and not path.startswith(root_path):
            return f"{root_path}{path}"
        return path
    
    return {"url_for": url_for, "root_path": root_path}

def render_template(template_name: str, request: Request, context: dict = None):
    """Helper function to render template with proper context"""
    if context is None:
        context = {}
    
    # Always include request
    context["request"] = request
    
    # Add template context (url_for, root_path, etc.)
    context.update(get_template_context(request))
    
    return templates.TemplateResponse(template_name, context)


@router.get("/auth/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """Login page - SuperTokens will handle authentication"""
    return render_template("supertokens_login.html", request, {
        "supertokens_enabled": True
    })


@router.get("/auth/logout")
async def logout(request: Request):
    """Logout - SuperTokens will handle session termination"""
    return RedirectResponse(url="/auth/signout", status_code=302)


@router.get("/auth/profile", response_class=HTMLResponse)
async def profile_page(
    request: Request,
    session: SessionContainer = Depends(verify_session())
):
    """User profile page with SuperTokens session"""
    user_id = session.get_user_id()
    
    return render_template("profile.html", request, {
        "user": {
            "id": user_id,
            "username": user_id,  # SuperTokens uses user_id as identifier
            "is_authenticated": True
        },
        "supertokens_enabled": True
    })


@router.get("/api/auth/me")
async def api_current_user(
    session: SessionContainer = Depends(verify_session())
):
    """Get current user info from SuperTokens session"""
    user_id = session.get_user_id()
    
    return {
        "success": True,
        "user": {
            "id": user_id,
            "username": user_id,
            "is_authenticated": True
        }
    }


@router.get("/api/auth/check")
async def api_check_auth(request: Request):
    """Check authentication status"""
    try:
        # Try to verify session without raising exception
        session = await verify_session()(request)
        if session:
            user_id = session.get_user_id()
            return {
                "authenticated": True,
                "user": {
                    "id": user_id,
                    "username": user_id,
                    "is_authenticated": True
                }
            }
    except:
        pass
    
    return {
        "authenticated": False,
        "user": None
    }


# Protected route example
@router.get("/dashboard")
async def dashboard(
    request: Request,
    session: SessionContainer = Depends(verify_session())
):
    """Dashboard page - requires authentication"""
    user_id = session.get_user_id()
    
    return render_template("dashboard.html", request, {
        "user": {
            "id": user_id,
            "username": user_id,
            "is_authenticated": True
        },
        "supertokens_enabled": True
    })
